package com.gxa.upload.service.impl;

import com.gxa.upload.service.UploadService;
import com.gxa.upload.uitl.QiNiuYun;
import com.gxa.upload.uitl.UUIDUtil;
import dto.ResultDTO;
import exception.SystemException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import org.springframework.web.multipart.MultipartFile;
import util.StringUtil;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

@PropertySource(value = "classpath:upload-config.properties", encoding = "utf-8")
@Service
public class UploadServiceImpl implements UploadService {
    @Value("${update.ext}")
    private String ext;
    @Value("${upload.path}")
    private String path;

    @Override
    public ResultDTO upload(MultipartFile file) throws IOException {
        if (file.isEmpty()) {
            throw new SystemException(1001,"请选择文件再上传！");
        }
        if (path==null){
            throw new SystemException(1001,"路径不能为空");
        }
        String filename = file.getOriginalFilename();
        if (!StringUtil.checkExt(ext, StringUtil.getExt(filename))) {
            throw new SystemException(1001,"只允许上传："+ext);
        }
//        //生成新的文件名
        String newFileName = uniqueName(filename);
//        // 生成一个时间的文件夹  /2021/01/28
        String datePath = StringUtil.getDatePath();
        path = path+datePath;
        StringUtil.createDirs(path);
        File dest = new File(path,newFileName);
        //上传
        file.transferTo(dest);
        QiNiuYun.upload(dest, datePath+"/"+newFileName);
        return new ResultDTO(200,"success", datePath+"/"+newFileName);
    }

    /**
     * 生成唯一的文件名
     * @param fileName
     * @return
     */
    private static String uniqueName(String fileName){
        // 重新生成一个当前系统中唯一的文件名
        String uid = UUIDUtil.getUid();
        String newFileName = uid + StringUtil.getExt(fileName);
        return newFileName;
    }


}
